package com.wadesss.flyingformationapp

import android.annotation.SuppressLint
import android.bluetooth.BluetoothDevice
import android.content.Intent
import android.graphics.Color
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import java.lang.Exception
import java.lang.reflect.Method
import java.util.*


class BluetoothItemAdapter(deviceList: MutableList<BluetoothItem>, activity: ConnectActivity) :
    RecyclerView.Adapter<BluetoothItemAdapter.ViewHolder>() {
    private var mDeviceList: MutableList<BluetoothItem> = deviceList
    var act = activity

    @SuppressLint("NewApi")
    open class ViewHolder(view: View, activity: ConnectActivity) : RecyclerView.ViewHolder(view) {
        val btn: Button = view.findViewById(R.id.join_conn_btn) as Button
        var deviceName: TextView = view.findViewById(R.id.bluetooth_name)
        var deviceMac: TextView = view.findViewById(R.id.bluetooth_address)

        init {
            btn.setOnClickListener { v ->
                try {

                    if (btn.text == "断开") {
                        if (App.instance.bluetoothSocket != null) {
                            App.instance.bluetoothSocket?.close()
                        }

                        Thread {
                            try {
                                val s = Intent("disconn")
                                s.putExtra("index", adapterPosition)
                                App.instance.localBroadcastManager.sendBroadcast(s)
                            }
                            catch (e: Exception) {
                                Handler(Looper.getMainLooper()).post {
                                    Toast.makeText(
                                            v.context,
                                            e.message, Toast.LENGTH_SHORT
                                    ).show()
                                }
                            }
                        }.start()

                        btn.text = "连接"
                        deviceName.setTextColor(Color.parseColor("#000000"))

                        App.instance.localBroadcastManager.sendBroadcast(Intent("enable.btn"))

                        return@setOnClickListener
                    }
                    else
                    {
                        Thread {
                            try {
                                val s = Intent("disable.btn")
                                s.putExtra("index", adapterPosition)
                                App.instance.localBroadcastManager.sendBroadcast(s)
                            }
                            catch (e: Exception) {
                                Handler(Looper.getMainLooper()).post {
                                    Toast.makeText(
                                            v.context,
                                            e.message, Toast.LENGTH_SHORT
                                    ).show()
                                }
                            }
                        }.start()

                        btn.text = "正在连接..."

                        App.instance.mClient.stopSearch()

                        Handler(Looper.getMainLooper()).postDelayed({
                            App.instance.mMac = deviceMac.text!!.toString()

                            val dev = App.instance.bluetoothManager.adapter.getRemoteDevice(deviceMac.text.toString())

                            val m1: Method = BluetoothDevice::class.java.getMethod("createBond")
                            m1.invoke(dev)

                            val uuid: UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")
                            App.instance.bluetoothSocket =
                                    dev.createInsecureRfcommSocketToServiceRecord(uuid)

                            if (App.instance.bluetoothSocket?.isConnected == true) {
                                App.instance.bluetoothSocket!!.close()
                            }

                            try
                            {
                                App.instance.bluetoothSocket?.connect()
                            }
                            catch (e: Exception) {
                                Toast.makeText(
                                        v.context,
                                        "无法连接该蓝牙", Toast.LENGTH_SHORT
                                ).show()
                                btn.text = "连接"
                                deviceName.setTextColor(Color.parseColor("#000000"))

                                App.instance.localBroadcastManager.sendBroadcast(Intent("enable.btn"))
                                return@postDelayed
                            }


                            if (App.instance.bluetoothSocket?.isConnected == true) {
                                Toast.makeText(
                                        v.context,
                                        "连接成功", Toast.LENGTH_SHORT
                                ).show()

                                btn.text = "断开"
                                btn.isEnabled = true

                                deviceName.setTextColor(Color.parseColor("#c75450"))

                                activity.findViewById<Button>(R.id.connection_btn).isEnabled = true
                            }

                        }, 100)
                    }

                } catch (e: Exception) {
                    Toast.makeText(
                        App.instance.applicationContext,
                        "蓝牙连接失败！请检查高频头是否正确接入遥控器", Toast.LENGTH_SHORT
                    ).show()
                    App.instance.localBroadcastManager.sendBroadcast(Intent("enable.btn"))
                }
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view: View = LayoutInflater.from(parent.context)
            .inflate(R.layout.bluetooth_item_layout, parent, false)
        return ViewHolder(view, act)
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val dev: BluetoothItem = mDeviceList[position]

        if (App.instance.bluetoothSocket?.isConnected == true)  {
            if (dev.device_name.isEmpty()) {
                holder.deviceName.text = dev.device_mac
            }
            else
            {
                holder.deviceName.text = "${dev.device_name}（${dev.device_mac}）"
            }

            holder.deviceMac.text = dev.device_mac
            holder.deviceName.visibility = View.VISIBLE

            if (dev.device_mac == App.instance.bluetoothSocket?.remoteDevice?.address)
            {
                holder.btn.isEnabled = true
                holder.deviceName.setTextColor(Color.parseColor("#c75450"))
                holder.btn.text = "断开"
            }
            else
            {
                holder.btn.isEnabled = false
            }
        }
        else
        {
            if (dev.device_name.isEmpty()) {
                holder.deviceName.text = dev.device_mac
            }
            else
            {
                holder.deviceName.text = "${dev.device_name}（${dev.device_mac}）"
            }

            holder.deviceMac.text = dev.device_mac
            holder.btn.visibility = View.VISIBLE
            holder.deviceName.visibility = View.VISIBLE
        }
    }

    override fun getItemCount(): Int {
        return mDeviceList.size
    }
}